import React, { Component } from 'react';
import { connect } from 'react-redux';
import '../Tracking/tracking-min.js';
import '../Tracking/data/face-min.js';
import '../Style/demo.css';
// import 'html5media/dist/api/1.2.1/html5media.min.js';
import { Tool } from '../Tool';
import Loading from "./Loading/Loading";

const key = "_JkYncWKOOXpbX2Y6xs0eP0AM8EhSFJk";
const secret = "yOcczaP279lbcVjCc-6SeDmKmXSaz-bb";

class Normal extends Component{
    constructor(props){
        super(props);
        console.log(props);
    }
    componentDidMount(){
        this.tracker = new tracking.ObjectTracker('face');
        this.handleLoad(this.tracker)
        // this.getFaceset(); // 已固定脸集
    }
    componentDidUpdate(){
        let {faceset_token} = this.props;
        if(!faceset_token){
            this.getFaceset();
        }
    }
    componentWillUnmount(){
        console.log("will unmount");
        console.log(tracking);
        if(this.trackerTask){
            this.trackerTask.stop();
        }
        if(this.video){
            this.video.pause(); 
            this.video.srcObject.getVideoTracks()[0].stop(); 
            // tracking-min.js 没有自定义对象srcObject（应该是压缩过程中丢失了）。

            // let videoSrcObject;
            // for (let key in this.video) {
            //     console.log(key,this.video[key])
            //     if(this.video[key] instanceof MediaStream){
            //         console.log(key);
            //         videoSrcObject = this.video[key];
            //         videoSrcObject.getVideoTracks()[0].stop();
            //     }
            // }          
            
            
        }
        
    }
    getFaceset(){
        let {dispatch} = this.props;
        Tool.post("/facepp/v3/faceset/getfacesets",{
            "api_key":key,
            "api_secret":secret
        },(response)=>{
            if(response.facesets.length > 0){
                let faceset = response.facesets[0];
                let faceset_token = faceset.faceset_token;
                dispatch({faceset_token,type:"SET_FACESET_TOKEN"});
            }else{
                this.createFaceset();
            }
        },(setting,xhr)=>{
            console.log("getfaceset error");
        })
    }
    createFaceset(){
        let {dispatch} = this.props;
        Tool.post("/facepp/v3/faceset/create",{
            "api_key":key,
            "api_secret":secret
        },(response)=>{
            let faceset_token = response.faceset_token;
            dispatch({faceset_token,type:"SET_FACESET_TOKEN"});
        },(setting,xhr)=>{
            console.log("create error");
        })
    }
    handleLoad = (tracker)=>{
        this.video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let face = document.getElementById('face');
        let context = canvas.getContext('2d');
       
        tracker.setInitialScale(4);
        tracker.setStepSize(2);
        tracker.setEdgesDensity(0.1);
        this.trackerTask = tracking.track('#video', tracker, { camera: true });
        tracker.on('track', (event) => {
            
            context.clearRect(0, 0, canvas.width, canvas.height);
            event.data.forEach(function(rect) {
            context.strokeStyle = '#a64ceb';
            context.strokeRect(rect.x, rect.y, rect.width, rect.height);
            context.font = '11px Helvetica';
            context.fillStyle = "#fff";
            context.fillText('x: ' + rect.x + 'px', rect.x + rect.width + 5, rect.y + 11);
            context.fillText('y: ' + rect.y + 'px', rect.x + rect.width + 5, rect.y + 22);
            });
            let {refresh,dispatch} = this.props;
            if(event.data.length > 0 && !refresh){
                face.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
                face.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                
                dispatch({type:"SET_REFRESH"})
                let src = face.toDataURL("image/jpeg");
                // let src = face.toDataURL("image/png");
                console.log(src.length);
                this.detectFace(src);
                
            }
        });
    }

    detectFace = (src) => {
        let {dispatch} = this.props;
        let errorTimer;
        Tool.post("/facepp/v3/detect",{
                    "api_key":key,
                    "api_secret":secret,
                    "image_base64":src.match(/,(.*)$/)[1],
                    "return_landmark":2,
                    "return_attributes":"gender,age"
                },(response) => {
                    if(response.faces.length > 0){
                        if(errorTimer){
                            clearTimeout(errorTimer);
                        }
                        dispatch({type:"SHOW_BUTTON"});
                        let faces = response.faces;
                        if(faces.length > 0){
                            this.searchFace(faces[0]);
                        }else{
                            alert("detect no face ")
                        }
                        
                    }
                },(setting,xhr) => {
                    console.log("detect error");
                    if(errorTimer){
                        clearTimeout(errorTimer);
                    }
                    errorTimer = setTimeout(()=>{
                        dispatch({type:"RESET_REFRESH"});
                    },1000);
                });
    }

    getFaceData = (face,face_token,confidence = 0) => {
        Tool.get("/api/getNamebyToken",{
            token:face_token
        },(response)=>{
            console.log(response);
            if(!response.name || confidence < 70){
                let name=prompt("检测到新面孔，请输入您的名字","")
                if (name!=null && name!=""){
                    // document.write("你好，" + name + "！今天过得好吗？")
                    this.saveFaceData(face_token,name);
                }
                
            }else{
                this.props.dispatch({type:"RESET_LOADING"});
                alert('age: ' + face.attributes.age.value +
                    '\ngender: ' + face.attributes.gender.value + 
                    '\nconfidence: ' + confidence +
                    '\nname: '+response.name);
            }
        },(setting,xhr)=>{
            console.log("get name error");
        });      
    }
    saveFaceData = (face_token, name) => {
        Tool.post("/api/saveNameAndToken",{
            token:face_token,
            name:name
        },(response)=>{
            console.log(response);
            if(response.result == 1){
                this.addFaceToFaceset(face_token);
            }
        },(setting,xhr)=>{
            console.log("save name error");
        })
    }
    searchFace = (face)=>{
        let {faceset_token} = this.props;
        let face_token = face.face_token;
        Tool.post("/facepp/v3/search",{
            "api_key":key,
            "api_secret":secret,
            "face_token":face_token,
            "faceset_token":faceset_token
        },(response) => {
            if(response.results && response.results.length > 0 && response.results[0].confidence > 70){
                let result = response.results[0];
                this.getFaceData(face,result.face_token,result.confidence);
            }else if(response.error_message){
                console.log(response.error_message);
                this.searchFace(face);
            }else{
                this.getFaceData(face,face_token);
            }
            
        },(setting,xhr) => {
            console.log("search fail");
            this.searchFace(face);
            // this.getFaceData(face,face_token);
        });
    }
    addFaceToFaceset = (face_token) =>{
        let {faceset_token,dispatch} = this.props;
        Tool.post("/facepp/v3/faceset/addface",{
            "api_key":key,
            "api_secret":secret,
            "faceset_token":faceset_token,
            "face_tokens":face_token
        },(response) => {
            console.log("addFaceToFaceset",response);
            if(response.error_message){
                this.addFaceToFaceset(face_token);
            }else{
                dispatch({type:"RESET_LOADING"});
            }
        },(setting,xhr) => {

        });
    }

    render(){
        // console.log(tracking);
        let {showBtn,dispatch} = this.props;
        return(
            <div> this is normal's view 
                <div className="demo-title">
                    <p><a href="http://trackingjs.com" target="_parent">tracking.js</a> － get user's webcam and detect faces</p>
                </div>
            
                <div className="demo-frame">
                    <div className="demo-container">
                        <video id="video" width="320" height="240" preload="auto" autoPlay loop muted controls ></video>
                        <canvas id="canvas" width="320" height="240"></canvas>
                        <canvas id="face" width="320" height="240" style={{display:"none"}}></canvas>
                        <div id="reset-btn" style={{marginTop:400,marginLeft:250,display:showBtn?"block":"none"}}>
                            <button onClick={() => dispatch({type:"RESET"})}>重置</button>
                        </div>
                        <Loading loading={this.props.loading} text="加载中" style={{position:"absolute",marginLeft:250}}  />
                    </div>
                </div>
            </div>
        );
    }
    
}

export default connect(state => state.Normal)(Normal);
// ,dispatch =>  {return {onClick:()=>console.log("click")}}